<template>
  <div class="min-h-screen flex items-center justify-center p-4 animate-fade-in">
    <div class="glass rounded-lg shadow-xl p-8 w-full max-w-md space-y-6 animate-slide-up">
      <h2 class="text-2xl font-bold text-center text-gray-900">登录</h2>
      
      <form @submit.prevent="handleLogin" class="space-y-4">
        <div>
          <label class="block text-sm font-medium text-gray-700">用户名</label>
          <input 
            type="text" 
            v-model="form.username" 
            required 
            class="input-field"
            placeholder="请输入用户名"
          >
        </div>
        
        <div>
          <label class="block text-sm font-medium text-gray-700">密码</label>
          <input 
            type="password" 
            v-model="form.password" 
            required 
            class="input-field"
            placeholder="请输入密码"
          >
        </div>
        
        <div v-if="error" class="text-red-600 text-sm text-center">
          {{ error }}
        </div>
        
        <button 
          type="submit" 
          :disabled="loading"
          class="w-full btn-primary disabled:opacity-50"
        >
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </form>
      
      <p class="text-center text-sm text-gray-600">
        还没有账号？ 
        <router-link to="/register" class="text-blue-600 hover:text-blue-800 transition-colors">
          注册
        </router-link>
      </p>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const authStore = useAuthStore()

const form = ref({
  username: '',
  password: ''
})

const error = ref('')
const loading = ref(false)

const handleLogin = async () => {
  error.value = ''
  loading.value = true

  try {
    const result = await authStore.login(form.value.username, form.value.password)

    if (result.success) {
      router.push('/home')
    } else {
      error.value = result.message
    }
  } catch (err) {
    error.value = '登录失败，请重试'
  } finally {
    loading.value = false
  }
}
</script>
